package com.zmn.plat.business.impl.product.categorybrand;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.plat.common.dto.brand.BaseBrandDRO;
import com.zmn.plat.model.entity.brand.BaseBrand;
import com.zmn.plat.model.entity.brand.BaseBrandQuery;
import com.zmn.plat.model.entity.product.categorybrand.CategoryBrandQuery;
import com.zmn.plat.services.interfaces.brand.BaseBrandService;
import com.zmn.plat.utils.bean.BeanCopyUtils;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.plat.business.interfaces.product.categorybrand.CategoryBrandBService;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.common.dictionary.PlatErrorCodeDict;
import com.zmn.plat.common.dto.product.categorybrand.CategoryBrandDRO;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.servcategory.ShowCategoryAssociationVO;
import com.zmn.plat.model.vo.product.categorybrand.CategoryBaseBrandVo;
import com.zmn.plat.services.interfaces.product.ServProductService;
import com.zmn.plat.services.interfaces.product.categorybrand.CategoryBrandService;
import com.zmn.plat.services.interfaces.servcategory.ShowCategoryAssociationService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author tanbiao
 * @description
 * @modifier
 * @since 2020/8/25 11:27
 **/
@Service
@Slf4j
public class CategoryBrandBServiceImpl implements CategoryBrandBService {
    @Resource
    private CategoryBrandService categoryBrandService;
    @Resource
    private ServProductService servProductService;
    @Resource
    private ShowCategoryAssociationService showCategoryAssociationService;
    @Resource
    private BaseBrandService baseBrandService;

    @Override
    public List<CategoryBrandDRO> listBrandByProductId(Integer productId) {
        if (!NumberUtil.isPositiveInteger(productId)) {
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PANAM_NULL, "产品ID不能为空");
        }
        ServProduct product = servProductService.findByKey(productId);
        if (Objects.isNull(product)) {
            log.warn("listBrandByProductId 产品不存在,productID={}", productId);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PRODUCT_PRODUCT_NO_DATA);
        }

        // 前台产品直接查询相应的品牌，后台产品需要查询出对应的后台分类再查品牌
        List<Integer> categList = new ArrayList<>();
        if (Objects.equals(product.getShowType(), ProductConsts.EC_PRODUCT_TYPE)) {
            categList.add(product.getCategId());
        }
        // 后台产品查询关联的前台分类再查询品牌
        else if (Objects.equals(product.getShowType(), ProductConsts.ERP_PRODUCT_TYPE)) {
            List<ShowCategoryAssociationVO> relations = showCategoryAssociationService.listByCategoryId(product.getServCategId(), product.getCategOneId(), product.getCategId());
            if (CollectionUtils.isEmpty(relations)) {
                log.warn("后台产品分类没有关联对应的前台产品分类,categId={},errorCode:{}", product.getCategId(), PlatErrorCodeDict.ERROR_CODE_PRODUCT_BACK_SHOW_PRODUCT_CATEGORY_NOT_RELATED);
                throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PRODUCT_BACK_SHOW_PRODUCT_CATEGORY_NOT_RELATED);
            }
            categList.addAll(relations.stream().map(e -> e.getShowCategId()).collect(Collectors.toList()));
        }

        List<CategoryBaseBrandVo> list = categoryBrandService.listByCategIdsAndStatus(categList, GlobalConsts.YES);

        BeanCopier copier = BeanCopier.create(CategoryBaseBrandVo.class, CategoryBrandDRO.class, false);
        if (!CollectionUtils.isEmpty(list)) {
            List<CategoryBrandDRO> retList = list.stream().map(e -> {
                CategoryBrandDRO dro = new CategoryBrandDRO();
                copier.copy(e, dro, null);
                return dro;
            }).collect(Collectors.toList());
            return retList;
        }

        return Collections.EMPTY_LIST;
    }

    @Override
    public List<CategoryBrandDRO> listBrandByCategIds(Integer servCategId, Integer categOneId, Integer categId) {
        // 查询出后台分类对应的前台二级分类
        List<ShowCategoryAssociationVO> showCategoryAssociationVOS = showCategoryAssociationService.listByCategoryId(servCategId, categOneId, categId);
        // 前台二级分类id，产品挂载这个分类上面的
        List<Integer> categIdList = showCategoryAssociationVOS.stream().map(e -> e.getShowCategId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(categIdList)) {
            return Collections.emptyList();
        }
        // 关联关系启用，品牌状态启用
        List<CategoryBaseBrandVo> list = categoryBrandService.listByCategIdsAndStatus(categIdList, GlobalConsts.YES);
        if (!CollectionUtils.isEmpty(list)) {
            BeanCopier copier = BeanCopier.create(CategoryBaseBrandVo.class, CategoryBrandDRO.class, false);
            List<CategoryBrandDRO> retList = list.stream().map(e -> {
                CategoryBrandDRO dro = new CategoryBrandDRO();
                copier.copy(e, dro, null);
                return dro;
            }).collect(Collectors.toList());
            return retList;
        }

        return Collections.EMPTY_LIST;
    }

    @Override
    public List<BaseBrandDRO> listBrandByCategId(Integer categId) {

        if (NumberUtil.isNullOrZero(categId)) {
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PANAM_NULL, "入参不能为null");
        }
        // 查询分类关联的品牌id集合
        CategoryBrandQuery query1 = new CategoryBrandQuery();
        query1.setCategId(categId);
        query1.setStatus(GlobalDict.YESNO_YES);
        List<Integer> brandIds = Optional.ofNullable(categoryBrandService.listByQuery(query1))
                .orElse(Collections.emptyList())
                .stream()
                .map(m -> m.getBrandId())
                .collect(Collectors.toList());

        // 查询品牌信息
        BaseBrandQuery query2 = new BaseBrandQuery();
        query2.setBrandIdList(brandIds);
        query2.setStatus(GlobalDict.YESNO_YES);
        List<BaseBrand> baseBrands = baseBrandService.listByQuery(query2);
        List<BaseBrandDRO> baseBrandDROS = BeanCopyUtils.copyProperties(baseBrands, BaseBrand.class, BaseBrandDRO.class, BaseBrandDRO::new);

        return baseBrandDROS;
    }
}
